package com.gulimall.auth.service.impl;

import cn.hutool.http.Header;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResp;
import com.atguigu.common.vo.SocialVO;
import com.gulimall.auth.config.OAuth2Config;
import com.gulimall.auth.feign.MemberFeignService;
import com.gulimall.auth.service.OAuth2Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description
 * @Author lhj
 * @Date 2024/3/9 11:34
 */
@Slf4j
@Service
public class OAuth2ServiceImpl implements OAuth2Service {

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 处理微博回调通知
     *
     * @param code 授权码
     * @return boolean
     */
    @Override
    public R loginCallback(String code) {
        try {
            log.info("OAuth2ServiceImpl.loginCallback Receive call param: {}", code);
            HttpResponse httpResponse = HttpRequest.post(getWeiboTokenUrl(code))
                    .header(Header.CONTENT_TYPE, "application/json")
                    .timeout(5000)
                    .execute();

            log.info("OAuth2ServiceImpl.loginCallback weibo get token result: {}", httpResponse.body());
            int status = httpResponse.getStatus();
            if (status != 200) {
                return R.error();
            }
            SocialVO socialVO = JSONObject.parseObject(httpResponse.body(), SocialVO.class);
            R r = memberFeignService.socialLogin(socialVO);
            if (r.getCode() != 0) {
                return R.error();
            }
            MemberResp memberResp = r.getData(new TypeReference<MemberResp>() {});
            if (memberResp == null) {
                return R.error();
            }
            return R.ok(memberResp);
        } catch (HttpException e) {
            log.error("OAuth2ServiceImpl.loginCallback exception call code : {} ,error: {}", code, e);
        }
        return R.ok();
    }

    public String getWeiboTokenUrl(String code) {
        return OAuth2Config.weiboTokenUrl + code;
    }

}
